﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Enemy : MonoBehaviour
{

    public float speed = 10;   //移动的速度
    public float hp = 150;  //敌人的血量
    private float totalHp;   //血量的变化
    public GameObject explosionEffect;   //敌人死亡的特效
    private Slider hpSlider;    //ui中的Slider组件
    private Transform[] positions;    //获取之前做好的路径数组
    private int index = 0;   //数组下标
   // private BuildManager money;

    // Use this for initialization
    void Start()
    {
        positions = Waypoints.positions;
        totalHp = hp;   //一开始变化的血量等于敌人的血量
        hpSlider = GetComponentInChildren<Slider>();  //获得敌人身上的ui中的Slider组件 显示血量的减少
    }

    // Update is called once per frame
    void Update()
    {
        Move();
    }

    //控制敌人的移动
    void Move()
    {
        if (index > positions.Length - 1)    //到达目的点
            return;

        //（目标位置 - 当前位置）（单位向量）
        transform.Translate((positions[index].position - transform.position).normalized * Time.deltaTime * speed);
        
        //判断两个点之间的距离
        if (Vector3.Distance(positions[index].position, transform.position) < 0.2f)
        {
            index++;
        }

        if (index > positions.Length - 1)   //到达终点
        {
            ReachDestination();   //调用销毁函数
        }
    }

    //达到终点时销毁
    void ReachDestination()
    {
        GameManager.Instance.Failed();
        GameObject.Destroy(this.gameObject);
    }

    //被炮塔攻击时敌人存活数量减1
    void OnDestroy()
    {
        EnemySpawner.CountEnemyAlive--;
        //money.ChangeMoney(100);

    }

    //敌人受到伤害扣血
    public void TakeDamage(float damage)
    {
        if (hp <= 0) return;  
        hp -= damage;
        hpSlider.value = (float)hp / totalHp;

        if (hp <= 0)  //血量为0
        {
            Die();   //销毁函数
        }
    }

    //敌人销毁函数
    void Die()
    {
        GameObject effect = GameObject.Instantiate(explosionEffect, transform.position, transform.rotation);   //创建特效
        Destroy(effect, 1.5f);   //销毁特效
        Destroy(this.gameObject);   //销毁自身
    }

}
